# 测试多端登录
import json
import socket
import struct
import threading
import uuid


# 监听下线通知
def task(s):
    print("task开始")
    command = struct.unpack('>I', s.recv(4))[0]  # 接收并解析(接收4个字节的无符号整数)
    num = struct.unpack('>I', s.recv(4))[0]  # 解析出数据的大小
    print('监听命令：', command)
    if command == 0x232a:
        print("收到下线通知，退出登录！")
        s.close


imei = str(uuid.uuid1())
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 9000))

# 这里的s是channel
t1 = threading.Thread(target=task, args=(s,))
t1.start()

## 基础数据  command 9000为登录0x2328
command = 0x2328
version = 2
clientType = 5
print("客户端类型", clientType)
appId = 10000
parseType = 0x0  # 消息解析类型 0x0为json
userId = 'ls1'

## 数据转换为byte类型
commandBtye = command.to_bytes(4, 'big')
versionByte = version.to_bytes(4, 'big')
clientTypeByte = clientType.to_bytes(4, 'big')
parseTypeByte = parseType.to_bytes(4, 'big')
appIdByte = appId.to_bytes(4, 'big')
imeiBytes = bytes(imei, "utf-8")
imeiLength = len(imeiBytes)
imeiLengthByte = imeiLength.to_bytes(4, 'big')
data = {"userId": userId}
jsonData = json.dumps(data)
body = bytes(jsonData, 'utf-8')
body_len = len(body)
bodyLenBytes = body_len.to_bytes(4, 'big')

s.sendall(
    commandBtye + versionByte + clientTypeByte + parseTypeByte + appIdByte + imeiLengthByte + bodyLenBytes + imeiBytes + body)
# for i in range(100):
#     s.sendall(
#         commandBtye + versionByte + clientTypeByte + parseTypeByte + appIdByte + imeiLengthByte + bodyLenBytes + imeiBytes + body)

while (True):
    i = 1 + 1
